import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:openchina/constants/constants.dart';

class CommonWebPage extends StatefulWidget {
  String title;
  String url;

  CommonWebPage({Key key, this.title, this.url})
      : assert(title != null),
        assert(url != null),
        super(key: key);

  @override
  _CommonWebPageState createState() => _CommonWebPageState();
}

class _CommonWebPageState extends State<CommonWebPage> {
  FlutterWebviewPlugin _flutterWebviewPlugin = FlutterWebviewPlugin();
  bool _isLoading = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _flutterWebviewPlugin.onStateChanged.listen((state) {
      if (state.type == WebViewState.startLoad) {
        print('CommonWebPageState WebViewState.startLoad: $state');
        if (mounted) { //转菊花消失  mounted 确保当前weiget 在当前渲染树上
          setState(() {
            _isLoading = true;
          });
        }
      }else if(state.type == WebViewState.finishLoad){
        print('CommonWebPageState WebViewState.finishLoad: $state');
        if (mounted) { //转菊花消失  mounted 确保当前weiget 在当前渲染树上
          setState(() {
            _isLoading = false;
          });
        }
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _flutterWebviewPlugin.close();
  }

  @override
  Widget build(BuildContext context) {
    List<Widget> _appBarTitle = [
      Text(
        widget.title,
        style: TextStyle(
          color: Color(AppColors.APPBAR),
        ),
      ),
    ];
    if (_isLoading) {
      _appBarTitle.add(
        SizedBox(
          width: 10.0,
        ),
      );
      _appBarTitle.add(CupertinoActivityIndicator());
    }
    return WebviewScaffold(
      url: widget.url,
      appBar: AppBar(
        title: Row(
          children: _appBarTitle,
        ),
        iconTheme: IconThemeData(color: Color(AppColors.APPBAR),),
      ),
      withJavascript: true,//允许执行js
      withLocalStorage: true,//允许本地存储
      withZoom: true,//允许网页放大缩小
    );
  }
}
